package com.iot.beidou;

import com.alibaba.fastjson.JSON;
import com.iot.common.utils.StringUtils;
import com.iot.device.domain.BeidouClient;
import com.iot.device.domain.BeidouEvent;
import com.iot.device.service.IBeidouClientService;
import com.iot.device.service.IBeidouEventService;
import com.iot.websocket.Topic;
import com.iot.websocket.WebSocketMessageSender;
import com.iot.websocket.message.EventMsgMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Cao.ning
 * @date 2023/7/26
 */
@Service
public class BeidouMsgService {
    private static final Logger logger = LoggerFactory.getLogger(BeidouMsgService.class);

    @Autowired
    private IBeidouClientService beidouClientService;
    @Autowired
    private IBeidouEventService beidouEventService;

    public void beidouMsgGet(String message)
    {
        // id=5,angleZ=169.218399,angleX=0.534860,angleY=1.127155,event_ID=2622
        logger.info("收到北斗转发消息：{}", message);
        int start = message.indexOf("id");
        if(start >= 0){
            message = message.substring(start, message.length());
        }
        String[] data = message.split(",");
        Map<String, String> msgMap = new HashMap();
        for(String item : data){
            String[] record = item.split("=");
            if(record.length == 2){
                String key = record[0];
                String value = record[1];
                msgMap.put(key, value);
            }
        }
        String clientNo = msgMap.get("id");

        Date now = new Date();
        BeidouClient client = beidouClientService.selectBeidouClientByClientNo(clientNo);
        if(client == null){
            client = new BeidouClient();
            client.setClientNo(clientNo);
            client.setClientName(clientNo);
            client.setAddTime(now);
            client.setLastTime(now);
            client.setDeptId(0L);
            client.setUserId(1L);
            client.setCreateTime(now);
            client.setCreateBy("系统注册");
            beidouClientService.insertBeidouClient(client);
        }
        client.setLastTime(now);
        if(msgMap.get("vbat") != null)
        {
            client.setVbat(msgMap.get("vbat"));
        }
        if(msgMap.get("heartBeat") != null)
        {
            client.setHeartBeat(msgMap.get("heartBeat"));
        }

        beidouClientService.updateBeidouClient(client);

        String eventId = msgMap.get("event_ID");
        if(StringUtils.isNotEmpty(eventId)){
            String positionX = msgMap.get("positionX");
            String positionY = msgMap.get("positionY");
            String positionZ = msgMap.get("positionZ");
            String angleX = msgMap.get("angleX");
            String angleY = msgMap.get("angleY");
            String angleZ = msgMap.get("angleZ");
            String Ii = msgMap.get("Ii");
            if(filterData(positionX, positionY, positionZ, angleX, angleY, angleZ, Ii)){
                return;
            }
            BeidouEvent event = new BeidouEvent();
            event.setEventId(eventId);
            event.setClientNo(clientNo);
            event.setOriginData(message);
            event.setEventTime(now);
            event.setEventDate(now);
            if(StringUtils.isNotEmpty(positionX)){
                // 位移
                float positionx = Math.abs(Float.parseFloat(positionX));
                float positiony = Math.abs(Float.parseFloat(positionY));
                float positionz = Math.abs(Float.parseFloat(positionZ));
                float max = Math.max(Math.max(positionx, positiony), positionz);
                event.setMaxValue(max);
                if(max == positionx){
                    event.setMaxValueType("positionX");
                }else if(max == positiony){
                    event.setMaxValueType("positionY");
                }else{
                    event.setMaxValueType("positionZ");
                }
                event.setEventType("position");
            }else if(StringUtils.isNotEmpty(angleX)){
                // 位移
                float anglex = Math.abs(Float.parseFloat(angleX));
                float angley = Math.abs(Float.parseFloat(angleY));
                float anglez = Math.abs(Float.parseFloat(angleZ));
                float max = Math.max(Math.max(anglex, angley), anglez);
                event.setMaxValue(max);
                if(max == anglex){
                    event.setMaxValueType("angleX");
                }else if(max == angley){
                    event.setMaxValueType("angleY");
                }else{
                    event.setMaxValueType("angleZ");
                }
                event.setEventType("angle");
            }else if(StringUtils.isNotEmpty(Ii)){
                // 位移
                float ii = Float.parseFloat(Ii);
                event.setMaxValue(ii);
                event.setMaxValueType("Ii");
                event.setEventType("Ii");
            }
            beidouEventService.insertBeidouEvent(event);
            event.setClient(client);
            WebSocketMessageSender.send(EventMsgMessage.getInstance(Topic.BEIDOU_EVENT_MSG, client.getDeptId(), JSON.parseObject(JSON.toJSONString(event))));
        }
    }

    /**
     * 处理rj程序里9.77的异常数据
     * @param values
     * @return
     */
    boolean filterData(String... values){
        for(String val : values){
            if(StringUtils.isNotEmpty(val) && val.startsWith("9.77")){
                return true;
            }
        }
        return false;
    }
}
